package ru.bytedog.oiot.counter.bot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import ru.bytedog.oiot.counter.bot.bean.AppAuthority;
import ru.bytedog.oiot.counter.bot.service.UserService;
import ru.bytedog.oiot.counter.bot.service.dashboard.UserOtpService;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final UserService userService;
    private final UserOtpService userOtpService;

    public SecurityConfig(UserService userService, UserOtpService userOtpService) {
        this.userService = userService;
        this.userOtpService = userOtpService;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/static/**", "/api/auth/**", "/auth/**").permitAll()
                        .anyRequest().hasRole(AppAuthority.ADMIN.name()))
                .formLogin(login -> login
                        .loginPage("/auth/login"))
                .logout(logout -> logout.logoutUrl("/auth/logout")
                        .clearAuthentication(true)
                        .invalidateHttpSession(true))
                .httpBasic(withDefaults())
                .sessionManagement(sessionManagement -> sessionManagement
                        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
        return http.build();
    }

    @Bean
    public OtpAuthenticationProvider authenticationProvider() {
        return new OtpAuthenticationProvider(userService, userOtpService);
    }

    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

}
